<template>
	<om-addpage style="padding-top: 35px;" :busCode="busCode" :menuName="menuName" @formSubmit="formSubmit" :showHistoryBtn="true">
		<om-autoform ref="autoform" :initConfigData="mainConfigData" :initValue="initValue"></om-autoform>
	</om-addpage>
</template>
<script>
	import {getFormFields,formValidation, changeEditor,autoChangeEditor,configSelectData,hasEditor,formShowLoading ,configFormEditor,getWorkCacheKey, setSubmitSubValue,changeConfigAttr} from '@/static/js/formUtil.js';
	import dateTimePicker from '@/static/js/dateTimePicker.js';
	import { mapState } from 'pinia';
	import {useLoginUserStore} from '@/stores/login-user.js';
export default {
	provide() {
		return {
			formPage: this
		};
	},
	data() {
		return {
			menuName: '部门年度培训需求审批表',
			busCode: 'HRS1110',
			formdata: {},
			mainConfigData: [],
			subConfigData: {},
			initValue: {},
			subEditorObj:{},//存放子表编辑器数据
			instCacheKey:'hr-train-instYearPlan-inst-cache',
		};
	},
	computed: {
		...mapState(useLoginUserStore, ['userName', 'userId'])
	},
	methods: {
		loadOtherData(instId) {
			let _that = this;
			var formdata = _that.$refs.autoform.formdata;
			_that.om.request('tposition/getPrimary', { instId:instId, }).then(res => {
				if (res.succeed) {
					var value = res.value;
					formdata.instPostId = value.id
					formdata.instPostName = value.postName
					formdata.instUserId = value.userId
					formdata.instUserName = value.userName
				} else {
					_that.om.toast(res.msg);
				}
			});
		},
		clearInst(){
			let _that = this;
			_that.$refs.autoform.clear('title1', 'instId');
			_that.$refs.autoform.clear('title1', 'parentInstId');
			_that.$refs.autoform.clear('title1', 'instPostId');
		},
		formSubmit() {
			let _that = this;
			var checkRes = formValidation(this.$refs.autoform.configData, this.formdata);
			if (checkRes) {
				this.om.toast(checkRes);
			} else {
				//子表提交数据赋值
				setSubmitSubValue()
				if (!_that.formdata.dataStr) {
					this.om.toast(this.subEditorObj['title2'].title+'不能为空');
					return;
				}
				if(_that.options.edit === "true"){
					_that.om.formSave('trainInstYearPlan/doUpdate', _that.formdata, _that)
				}else{
					_that.om.formSave('trainInstYearPlan/doAdd', _that.formdata, _that)
				}
			}
		},
		getYearlist(){
			let _that = this
			let oldYear = ""
			if(_that.edit){
				oldYear = _that.formdata.year			
			}
			_that.om.request("common/findYearList",{after:1,oldYear: _that.formdata.year}).then(res=>{
				_that.$refs.autoform.changeEditor("title1","year","data",configSelectData(res,"text","value"))
				if(_that.options.edit === "true"){
					_that.$refs.autoform.initSelectIndex("title1","year")
				}
			})
		},
		initLoad(fileId) {
			let _that = this;
			if (!this.busCode) {
				return;
			}
			//表单字段
			var pro1 = this.om.request('formFieldConfig/addPage', { code: this.busCode });
			//制表岗位
			var pro2 = this.om.request('wxPosBusiAuth/isnewList', { code: this.busCode }, 'post');
			var pro3 =""
			if(fileId){
				pro3 = this.om.request("trainInstYearPlan/getValue",{ fileId:fileId})
			}
			var ajaxArr = [pro1,pro2,pro3];
			//多个AJAX全部完成时开始执行
			Promise.all(ajaxArr).then(res => {
					if (res[0].succeed) {
						let data = res[0].value;
						var mainData = configFormEditor(data)
						changeEditor(mainData[0].editors, "zuserId",{
							defaultValue:_that.userId,
							defaultName:_that.userName
						})
						//制表岗位
						changeEditor(mainData[0].editors, 'zposId', 'data', configSelectData(res[1], 'id', 'posname'));
						//培训相关信息课程信息
						changeConfigAttr("title2", "title", _that.subEditorObj["title2"].title,mainData)
						changeEditor("title2", "dataStr",{
							title: _that.subEditorObj["title2"].title.substr(1),
							titleTemplate:"培训项目名称: <%= projectName %>",
							subtitle1Template:"<%= startDateObjName %> ~ <%= endDateObjName %>",
							subtitle2Template:"培训方式: <%= trainTypeName %>"
						}, null, mainData)
						changeEditor("title1", "instId",{
							link: '/pages/public/search/search',
							linkParam: {
								other: JSON.stringify({
									containBoard: true
								}),
								method: 'post',
								namefield: 'instname',
								likefield: 'instname',
								initload: true,
								url: 'tinstitution/findNotBoard1',
								cachename: _that.instCacheKey,
								placeholder: '请输入机构名称'
							},
						},null,mainData)
						_that.$refs.autoform.configData = mainData;
						
						if(fileId){
							let fieldArr = getFormFields(mainData)
							fieldArr.push("id")
							for(let index in res[2].value){
								if(fieldArr.includes(index)){
									_that.$refs.autoform.$set(_that.$refs.autoform.formdata,index,res[2].value[index])
									_that.$set(_that.formdata,index,res[2].value[index])
								}
							}
							let dataList = _that._.cloneDeep(res[2].value.dataList)
							for(let item of dataList){
								item.userPostName = item.userName
							}
							_that.subEditorObj['title2'].workList = dataList
							_that.$refs.autoform.$set(_that.$refs.autoform.formdata,"dataStr",JSON.stringify(dataList))
							_that.$set(_that.formdata,"dataStr",JSON.stringify(dataList))
							delete res[2].value.dataList
							_that.$refs.autoform.initSelectIndex("topinfo","zposId")
						}
						_that.getYearlist()
					} else {
						_that.om.toast(res[0].msg);
						
					}
					_that.$nextTick(function(){
						if(_that.$refs.autoform.hasEditor('topinfo','zposId')){
							if(!_that.$refs.autoform.formdata.zposId){
								_that.$refs.autoform.initSelectVal("topinfo","zposId")
							}
						}
					})
				})
				.catch(err => {
					console.log(err);
				});
		},
	},
	onLoad(options) {
		let _that = this;
		_that.menuName = options.title || '部门年度培训需求审批表';
		uni.setNavigationBarTitle({
			title: _that.menuName
		});
		formShowLoading(_that)
		_that.busCode = options.code || "HRS1110";
		_that.formdata.userId = this.userId;
		_that.initLoad(options.fileId);
	},
	onShow() {
		let _that = this;
		if (_that.$refs.autoform) {
			for(var fieldId in _that.subEditorObj){
				var editor = _that.subEditorObj[fieldId]
				uni.getStorage({
					key: getWorkCacheKey(fieldId),
					success: function(res) {
						for(let item of res.data){
							if(item.abilityList === ""){
								item.abilityList = null
							}
						}
						editor.workList = res.data;
						uni.removeStorage({
							key: getWorkCacheKey(fieldId)
						});
					}
				});
			}
			uni.getStorage({
				key: _that.instCacheKey,
				success: function(res) {
					if (res.data) {
						let d = res.data;
						var formdata = _that.$refs.autoform.formdata;
						formdata.instId = d.id;
						formdata.instName = d.instname;
						formdata.parentInstId = d.parentinstId;
						formdata.parentInstName = d.parentinstName;
						_that.loadOtherData(d.id);
						uni.removeStorage({
							key: _that.instCacheKey
						});
					}
				}
			});
		}
	}
};
</script>
<style></style>
